import React, { useEffect, useState } from 'react';
import { Select, notification } from 'antd';
import { fetchApi } from '../../general/api';

interface ProjectOption {
    value: string;
    label: string;
}

interface SelectProjectProps {
    selectedCity: string | undefined; // 选中
    onCityChange: (value: string, label: string) => void; // 处理选择的回调  
    style?: React.CSSProperties;
}

const SelectProject: React.FC<SelectProjectProps> = ({ selectedCity, onCityChange, style }) => {
    const [ProjectOptions, setProjectOptions] = useState<ProjectOption[]>([]);

    // 请求数据  
    const fetchProjectOptions = async () => {
        try {
            const response = await fetchApi('/easymonitor/api/project'); // 使用 fetchApi
            const projects = response.map((project: any) => ({
                value: project.project_id, // 确保有唯一 key  
                label: project.project_name
            }));
            setProjectOptions(projects); // 更新数据源  
            notification.success({
                message: '请求成功', description: '项目数据查询成功。', duration: 2 // 2秒后自动关闭
            });
        } catch (error) {
            notification.error({
                message: '请求失败', description: '项目数据查询失败:' + error, duration: 2
            });
        }
    }

    useEffect(() => {
        fetchProjectOptions(); // 组件挂载时请求数据  
    }, []);

    // 处理选择变化  
    const handleChange = (value: string) => {
        const selectedOption = ProjectOptions.find(option => option.value === value);
        const label = selectedOption ? selectedOption.label : '';
        onCityChange(value, label); // 将 value 和 label 一起返回父组件  
    };

    return (
        <Select
            style={style}
            showSearch
            value={selectedCity} // 使用 selectedCity 来控制选择的值
            onChange={handleChange} // 更新选中的值
            options={[{ value: "", label: '所有项目' }, ...ProjectOptions]} // 预置一个选项  
        />
    );
};

export default SelectProject;
